import { Controller, Get, InternalServerErrorException, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
import { AdminService } from './admin.service';
// 导入文件拦截器
import { FileInterceptor } from '@nestjs/platform-express';

// import * as url from 'url';
import * as qiniu from 'qiniu';

@Controller()
export class AdminController {
  constructor(private readonly adminService: AdminService) {}

  // 上传图片api
  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))  // 拦截器(文件拦截器('file'))
  async upload(@UploadedFile('file') file) {  // UploadedFile 上传文件
    // console.log(file)
    const url = `http://localhost:3000/uploads/${file.filename}`;
    // 返回图片的信息
    return {
      "errno": 0,
      "data": [
        {
          url
        }
      ]
    };  
  }

  // 组件上传图片的 token，前端必须先获取这个 token
  @Get('key')
  getkey() {
    var accessKey = 'dg87lClBFLrluuIyKP8-oVS5YaYyWqlG2mukaJmo';
    var secretKdy = 'D7BkyrvQixBpRGuXOtOgNf3M2msgn2GLrsTwzre_';
    var mac = new qiniu.auth.digest.Mac(accessKey, secretKdy);
    var options = { 
      scope: 'mtbx', 
    };
    var putPolicy = new qiniu.rs.PutPolicy(options);
    var uploadToken = putPolicy.uploadToken(mac);

    return {
      token: uploadToken
    };
  }
}
